package com.hisense.settings;


import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.IWindowManager;
import android.view.InputDevice;
import android.content.DialogInterface.OnKeyListener;
import android.view.KeyEvent;
import java.io.IOException;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.os.SystemClock;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.PowerManager;
import android.os.Bundle;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.Calendar;
import com.android.settings.R;

import com.hisense.settings.util.Wrapper;

public class PowerOffService extends Service{
	private static int iCount = 60;
	protected ContextWrapper context;
	private static PowerOffService mPowerOffService;
	private static long time;
	private static AlertDialog        localDialog = null;
	private static final int    MSG_SET_POWEROFF_TIMER = 1;
	private static final int    MSG_COUNT_DOWN_1S = 2;
//	private long time=0;
	private static long settime[] = new long[8]; 
	private Wrapper mwrapper=null;	
	SharedPreferences.Editor editor;
	
	private Handler  timeHandler = new Handler()
    {
        public void handleMessage(
                android.os.Message msg)
        {
            super.handleMessage(msg);
            if (msg.what == MSG_SET_POWEROFF_TIMER)
            {
			Log.i("3333333", "&&&&&&&&&&&&&&&");
            		showCountDownDialog();
            		timeHandler.sendEmptyMessageDelayed(MSG_COUNT_DOWN_1S, 1000);
            }
			  else if(msg.what == MSG_COUNT_DOWN_1S)
		      {
		      		if(iCount > 0)
					{
						iCount--;
						localDialog.setMessage(getString(R.string.count_down_hint_head).toString() + " " + iCount + " " + getString(R.string.count_down_hint).toString());
						timeHandler.sendEmptyMessageDelayed(MSG_COUNT_DOWN_1S, 1000);
	      			}
					else
					{
						//power off
//						localDialog.dismiss();
//					if(false)
//					{
//						long mDownTime = SystemClock.uptimeMillis();  
//					    long when = mDownTime;  
//					    final KeyEvent keyPower = new KeyEvent(mDownTime, when, KeyEvent.ACTION_UP, 26, 0,  
//									 0, -1, 0, KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, InputDevice.SOURCE_KEYBOARD);  
//
//						IWindowManager mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));  
//					    try{  
//					        mWindowManager.injectInputEventNoWait(keyPower); 
//							
//					    } catch (RemoteException ex) { 
//					    
//					    } 
//					}
//					else
//					{
						localDialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
						intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						
//					}
					}
			  }

        };
    };
		private  void showCountDownDialog() 
		
		{
			iCount = 60;
			{			
			Log.i("3333333", 333+"");
			AlertDialog.Builder builder = new Builder(PowerOffService.this);		
			builder.setTitle(R.string.power_off);
			builder.setMessage(getString(R.string.count_down_hint_head).toString() + " " + iCount + " " + getString(R.string.count_down_hint).toString());
			builder.setPositiveButton(android.R.string.ok, new OnClickListener(){
				
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
					intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}});
			builder.setNegativeButton(android.R.string.cancel, new OnClickListener(){
				
				public void onClick(DialogInterface dialog, int which) {
					timeHandler.removeMessages(MSG_COUNT_DOWN_1S);
					dialog.dismiss();
					return ;
				}});
			localDialog=builder.create();
			localDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);			
			localDialog.show();
			
//			localDialog.setOnKeyListener(new OnKeyListener() {
//			     
//			    @Override
//			    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//			      
//				    Log.i("888", "setOnKeyListener");
//				    {
//						timeHandler.removeMessages(MSG_COUNT_DOWN_1S);
//						localDialog.dismiss();
//					    return true;
//				    }
//			    }
//		    });
			}
		}
				
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
	super.onCreate();
	IntentFilter intentFilter = new IntentFilter();
	intentFilter.addAction("com.google.poweroff");
	this.registerReceiver(new PowerOffReciver(), intentFilter);
	SharedPreferences mSetPowerOfftimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
		
		editor = mSetPowerOfftimer.edit();		
		editor.putLong("current_time", System.currentTimeMillis());
		editor.commit();
	
	long off_time=0;
	//off_time=mSetPowerOfftimer.getLong("off_time",1);
	off_time=powerofftime();
	Log.i("off_time",off_time+"!!!!!!$$$$$$$$$");
	if(off_time>0)
			{
			
			Log.i("before_power_on",off_time-System.currentTimeMillis()+"");
			timeHandler.removeMessages(MSG_SET_POWEROFF_TIMER);
			timeHandler.sendEmptyMessageDelayed(MSG_SET_POWEROFF_TIMER, off_time);
			}
			else
			{
			timeHandler.removeMessages(MSG_SET_POWEROFF_TIMER);
			}
			mwrapper = Wrapper.getWrapperInstance();
	        SharedPreferences mSetPowerOntimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
			
	        PowerOnTimer pr = new PowerOnTimer();
	        long ontime=pr.Powerontime(mSetPowerOntimer, pr.getPoweronTime());
	        int power_on=(int)ontime/60000;			
			//power on tv
	        mwrapper.setWakeupTimer(power_on);
			Log.i("power_on",power_on+"$$$$$$$$$$$$$$$$");
	}
		
		
	private class PowerOffReciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			mwrapper = Wrapper.getWrapperInstance();
	        SharedPreferences mSetPowerOntimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE);
			
	        PowerOnTimer pr = new PowerOnTimer();
	        long ontime=pr.Powerontime(mSetPowerOntimer, pr.getPoweronTime());
	        int power_on=(int)ontime/60000;			

			//power on tv
	        mwrapper.setWakeupTimer(power_on);
	        Log.i("ontime",ontime+"$$$$$$$$$$$$$$$$");
	        Log.i("power_on",power_on+"&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
						
			String action = intent.getAction();
			if(action.equals("com.google.poweroff")) {
				Bundle bundle = intent.getExtras();
	//			long poweroff_time=bundle.getLong("PowerOff_Time");
				  
	time=powerofftime();
				Log.i("time",time+"");
				if(time<=0){
					timeHandler.removeMessages(MSG_SET_POWEROFF_TIMER);
					
				}else
				{
					Log.i("time4",time+"");
					timeHandler.removeMessages(MSG_SET_POWEROFF_TIMER);
				    timeHandler.sendEmptyMessageDelayed(MSG_SET_POWEROFF_TIMER, time);
				}
				
			}
		}
		
	}	

	private long powerofftime(){
	
	SharedPreferences mSetPowerOfftimer = getSharedPreferences("com.android.settings_preferences", Context.MODE_PRIVATE); 
    SharedPreferences offuseontime = PreferenceManager.getDefaultSharedPreferences(this);
			Boolean off_use_on_time=offuseontime.getBoolean("off_use_on_time",false);
			Boolean off_once=offuseontime.getBoolean("off_once",false);
			Boolean off_week_monday=offuseontime.getBoolean("off_week_monday",false);
			Boolean off_week_tuesday=offuseontime.getBoolean("off_week_tuesday",false);			
			Boolean off_week_wednesday=offuseontime.getBoolean("off_week_wednesday",false);
			Boolean off_week_thursday=offuseontime.getBoolean("off_week_thursday",false);
			Boolean off_week_friday=offuseontime.getBoolean("off_week_friday",false);
			Boolean off_week_saturday=offuseontime.getBoolean("off_week_saturday",false);
			Boolean off_week_sunday=offuseontime.getBoolean("off_week_sunday",false);
									
			Calendar c = Calendar.getInstance();
			int today = c.get(Calendar.DAY_OF_WEEK); //Get what day is it today
			Log.i("today",today+"");
			
			long poweroff_time=mSetPowerOfftimer.getLong("off_time",0);
	long currenttime=mSetPowerOfftimer.getLong("current_time",System.currentTimeMillis()); //Get current time
			
	if(off_use_on_time==false)
				{
					time=0;
					Log.i("time1",time+"");
				}
				else
				{
				
				
					if(off_once==true)
					{
						time=poweroff_time-currenttime;	
						Log.i("time2",time+"");
					}
					else
					{
						if(off_week_monday==true)
						{
							settime[0]=poweroff_time-currenttime+(1-today+1+7)%7*24*60*60*1000;
							Log.i("settime[0]",settime[0]+"");
						}else
						{
							settime[0]=0;
						}
						if(off_week_tuesday==true)
						{
							settime[1]=poweroff_time-currenttime+(2-today+1+7)%7*24*60*60*1000;
							Log.i("settime[1]",settime[1]+"");
						}else
						{
							settime[1]=0;
						}
						if(off_week_wednesday==true)
						{
							settime[2]=poweroff_time-currenttime+(3-today+1+7)%7*24*60*60*1000;
							Log.i("settime[2]",settime[2]+"");
						}else
						{
							settime[2]=0;
						}
						if(off_week_thursday==true)
						{
							settime[3]=poweroff_time-currenttime+(4-today+1+7)%7*24*60*60*1000;
							Log.i("settime[3]",settime[3]+"");
						}else
						{
							settime[3]=0;
						}
						if(off_week_friday==true)
						{
							settime[4]=poweroff_time-currenttime+(5-today+1+7)%7*24*60*60*1000;
							Log.i("settime[4]",settime[4]+"");
						}else
						{
							settime[4]=0;
						}
						if(off_week_saturday==true)
						{
							settime[5]=poweroff_time-currenttime+(6-today+1+7)%7*24*60*60*1000;
							Log.i("settime[5]",settime[5]+"");
						}else
						{
							settime[5]=0;
						}
						if(off_week_sunday==true)
						{
							settime[6]=poweroff_time-currenttime+(7-today+1+7)%7*24*60*60*1000;
							Log.i("settime[6]",settime[6]+"");
						}else
						{
							settime[6]=0;
						}
						if(off_once==false&&off_week_monday==false&&off_week_tuesday==false&&off_week_wednesday==false&&off_week_thursday==false
				&&off_week_friday==false&&off_week_saturday==false&&off_week_sunday==false)
					{
						settime[7]=poweroff_time-currenttime;	
						Log.i("settime[7]",settime[7]+"");
					}
						else
						{
							settime[7]=0;
						}
						
						//for list ,sort by time
			        	for(int i=0;i<settime.length;i++){
			        		Log.i("i","!!!!!!!!!!"+i);	        		
			        		for(int j=i+1;j<settime.length;j++)
			        		{
			        			if(settime[i]>settime[j]){
			        				long temp=settime[i];
			        				settime[i]=settime[j];
			        				settime[j]=temp;			        				
			        			}        					
			        		}
			        		Log.i("settime","....@"+settime[i]);
			        	}
			        	
			        	for(int k=0;k<settime.length;k++)
			        	{
			        		Log.i("time","%%%%%%"+k);
			        		Log.i("time","--..#"+settime[k]);
			        		Log.i("time","@@@@@@@@@@@@@"+settime.length);
			        		
			        		if(settime[k]>0)
			        			{
			        			Log.i("time","$$$$$$$$$$$$$$"+settime[k]);
			        			time=settime[k];
			        		Log.i("time3",time+"");
			        		break;
			        		}			        		
			        	}														        	
					}											
				}
	return time;
	}
}
